package cn.wolfcode.shop.cloud.mq;

import cn.wolfcode.shop.cloud.msg.SeckillCodeMsg;
import cn.wolfcode.shop.cloud.service.ISeckillOrderInfoService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@RocketMQMessageListener(
        consumerGroup = MQConstans.CREATE_ORDER_GROUP,
        topic = MQConstans.CREATE_ORDER,
        selectorExpression = MQConstans.CREATE_ORDER_TAG
)
@Component
public class OrderCreateMQListener implements RocketMQListener<OrderMessage> {

    @Autowired
    private ISeckillOrderInfoService seckillOrderInfoService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(OrderMessage orderMessage) {

        System.out.println("进入到创建订单的消费者中");
        //从rocketmq消息中间件中能拿出数据  执行秒杀的操作
        Long seckillId=orderMessage.getSeckillId();
        Long userId=orderMessage.getUserId();
        String uuid = orderMessage.getUuid();
        HashMap<String, Object> data = new HashMap<>();
        data.put("seckillId",seckillId);
        data.put("userId",userId);
        data.put("uuid",uuid);
        try {
            //int i=1/0;
            String orderNo = seckillOrderInfoService.doSeckill(userId, seckillId);
            data.put("data",orderNo);
            //异步下单成功
            data.put("code",200);
            rocketMQTemplate.syncSend(MQConstans.CREATE_ORDER_SUCCESS_DEST,data);
        } catch (Exception e) {
            e.printStackTrace();
            //异步下单失败
            data.put("msg", SeckillCodeMsg.SECKLILL_FAIL.getMsg());
            data.put("code", SeckillCodeMsg.SECKLILL_FAIL.getCode());
            rocketMQTemplate.syncSend(MQConstans.CREATE_ORDER_FAIL_DEST,data);
        }

    }
}
